//
//  Regex.swift
//  SwiftTips-Mid
//
//  Created by wangxi on 2016/11/10.
//  Copyright © 2016年 wangxi. All rights reserved.
//

import Foundation

struct Regex: ActionRunnable {
    
    static func run() {
        
        let mailPattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
        
//        let matcher: RegexHelper
//        
//        do {
//            matcher = try RegexHelper(mailPattern)
//            
//            let maybeMailAdress = "wangxi@gmail.com"
//            
//            if matcher.match(maybeMailAdress) {
//                print("有效邮箱地址")
//            } else {
//                print("无效的邮箱")
//            }
//            
//        } catch {
//            
//        }
        
        if "wangxi@wangxi.com" =~ mailPattern {
            print("有效")
        } else {
            print("无效")
        }
        
        if ":大笑:" =~ ":.*:" {
            print("表情：大笑")
        } else {
            print("无效表情")
        }
        
    }
}

struct RegexHelper {
    let regex: NSRegularExpression
    
    init(_ pattern: String) throws {
        try regex = NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    }
    
    func match(_ input: String) -> Bool {
        let matches = regex.matches(in: input, options: [], range: NSMakeRange(0, input.utf16.count))
        return matches.count > 0
    }
}

precedencegroup MatchPrecedence {
    associativity: none
    higherThan: DefaultPrecedence
}

infix operator =~: MatchPrecedence

func =~(lhs: String, rhs: String) -> Bool {
    do {
        return try RegexHelper(rhs).match(lhs)
    } catch _ {
        return false
    }
}
